using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Texture2D img1;
	public Texture2D img2;
	public Texture2D imgBack;
	private int baseX;
	private int baseY;
	private int player;
	private int result;
	private int [,] matrix2D;
	private int [] repent;
	private GUIStyle fontStyle;
	
	void OnGUI()
    {
		drawMenu();

		drawChesses();

		drawState();

    }

	void drawMenu(){
		GUI.Box(new Rect(550, 30, 100, 90), "Menu");

		if (GUI.Button(new Rect(560, 60, 80, 20), "restart"))
			Reset();
		if (result == 0 && GUI.Button(new Rect(560, 90, 80, 20), "repent"))
			Repent();
	}

    void Start()
    {
		Reset();

		fontStyle = new GUIStyle();  
        fontStyle.normal.background = null;   
        fontStyle.normal.textColor= new Color(1, 1, 1);    
        fontStyle.fontSize = 60; 
		
    }

	void Reset()
	{
		baseX = 25;
		baseY = 10;
		player = 0;
		result = 0;

		matrix2D = new int [3,3]
		{
			{0,0,0},
			{0,0,0},
			{0,0,0}
		};
		repent = new int [2] {0,0};
	
	}

	void Repent()
	{
		player ++;
		matrix2D[repent[0],repent[1]] = 0;
	}

	void drawChesses(){
		for(int i = 0;i < 3;i ++ )
		{
			for(int j = 0;j < 3;++ j)
			{
				if(matrix2D[i,j] == 1)
					GUI.Button(new Rect(baseX + 150*i, baseY + 150*j, 150, 150), img1);
				else if(matrix2D[i,j] == 2)
					GUI.Button(new Rect(baseX + 150*i, baseY + 150*j, 150, 150), img2);
				else if(result != 0)
				{
					GUI.Button(new Rect(baseX + 150*i, baseY + 150*j, 150, 150), imgBack);
				}
				else
				{
					if(GUI.Button(new Rect(baseX + 150*i, baseY + 150*j, 150, 150), imgBack))
					{
						
						matrix2D[i,j] = 1 + player % 2;
						repent[0] = i; 	repent[1] = j;
						result = check();
						player ++;
					}
				}
			}
		}
	}
	
	int check()
	{
		for(int i = 0;i < 3;i ++)
		{
			if(matrix2D[i,0] == matrix2D[i,1] && matrix2D[i,1]== matrix2D[i,2] && matrix2D[i,0] != 0)
				return matrix2D[i,0];
			if(matrix2D[0,i] == matrix2D[1,i] && matrix2D[1,i]== matrix2D[2,i] && matrix2D[0,i] != 0)
				return matrix2D[0,i];
		}
		if(matrix2D[0,0] == matrix2D[1,1] && matrix2D[1,1] ==matrix2D[2,2]) 
			return matrix2D[1,1];
		if(matrix2D[0,2] == matrix2D[1,1] && matrix2D[1,1] ==matrix2D[2,0]) 
			return matrix2D[1,1];
		return 0;
	}

	void drawState(){
		if (result == 1) 
		{    
			GUI.Label (new Rect (550, 300, 150, 150), "Player1 wins!", fontStyle);    
		} 
		else if (result == 2) 
		{    
			GUI.Label (new Rect (550, 300, 150, 150), "Player2 wins!", fontStyle);    
		} 
		else 
		{
			GUI.Label (new Rect (550, 300, 150, 150), "Playing...", fontStyle);
		} 
	}

    void Update(){
        
    }
}
